//
//  DDOAuthViewModel.swift
//  swift微博
//
//  Created by whitcast on 16/7/13.
//  Copyright © 2016年 whitcast. All rights reserved.
//

import UIKit
//OAuth的网络请求
class DDOAuthViewModel: NSObject {
    //单例对象
    static let shardOAuthVM :DDOAuthViewModel = DDOAuthViewModel()
    
    // MARK:---根据授权码加载数据
    func getApptoken(code: String?,callBack:(isSuccess :Bool)->()) {
        //抽取到了tool网络工具类
        DDHTTPSessionManagerTool.shardTool.getCode(code ?? "") { (response, error) -> () in
            if error != nil {
                print(error)
                callBack(isSuccess: false)
                return
            }
            guard let dict = response as? [String :AnyObject] else {
                print("返回的json格式有问题")
                callBack(isSuccess: false)
                return
            }
            
            //字典转模型
            let model = DDUserAccountModel.init(dic: dict)
            
            print(model)
            //获取用户数据
            self.getUserAccount(model,callBack: callBack)//有值
            
        }
        
    }
    
    
    // MARK:--获取用户数据
   private func getUserAccount(model : DDUserAccountModel,callBack:(isSuccess :Bool)->()) {
        DDHTTPSessionManagerTool.shardTool.getUserAccount(model) { (response, error) -> () in
            if error != nil {
                print(error)
                callBack(isSuccess: false)
                return
            }
            guard let dict = response as? [String :AnyObject] else {
                print("返回的json格式有问题")
                callBack(isSuccess: false)
                return
            }
            //字典转模型
            let  model1 = DDUserAccountModel.init(dic: dict)
            model1.access_token = model.access_token
            model1.expires_in = model.expires_in
            
           //归档
            let result = model1.storeData(model1)
            
            callBack(isSuccess: result)
            
        }
        
    }

}
